package com.hbgc.controller;

import com.hbgc.entity.User;
import com.hbgc.ocnstant.Constants;
import com.hbgc.service.LoginService;
import com.hbgc.utils.EncryptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/admin")
public class LoginController {

   @Autowired
    private LoginService loginService;

    @RequestMapping("/loginPage")
    public String loginPage(){

        return "/admin/login/login";
    }

    @RequestMapping("/loginByUser")
    public String loginByUser(String username, String password, RedirectAttributes r, HttpServletRequest request) {


           User user = loginService.findByUsername(username,0);
           if (user==null) {
               r.addFlashAttribute("errMsg", "用户名不存在");
               return "redirect:/admin/loginPage";
           } else if (!user.getPassword().equals(EncryptionUtils.encryptMD5(password))) {
               r.addFlashAttribute("errMsg", "密码不正确");

               return "redirect:/admin/loginPage";
           } else {
               request.getSession().setAttribute(Constants.ADMIN_SESSION_CODE, username);
               return "/admin/index/index";
           }




    }
    //退出登录 admin/logout
    @RequestMapping("logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        System.out.println(123456);
        Object user = request.getSession().getAttribute(Constants.ADMIN_SESSION_CODE);
        if (user!=null){
            request.getSession().removeAttribute(Constants.ADMIN_SESSION_CODE);
            System.out.println(user + " 退出成功");
        }
        return "/admin/login/login";
    }



}
